package com.study.tiger.controller;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.qrcode.QRCodeWriter;
import com.itextpdf.text.pdf.qrcode.WriterException;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import io.swagger.annotations.*;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdfwriter.ContentStreamWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.*;

/**
 * @Author: liutingting
 * @Date: 2022/3/14 001416:41
 * @Version: 1.0
 */
@RestController
@RequestMapping("/v1/pdf")
@Api(tags="PDF操作接口")
public class PdfController {

    @GetMapping("deleteImg")
    @ApiOperation(value = "删除PDF文件上的图片", notes = "删除PDF文件上的图片")
    @ApiImplicitParams({
         @ApiImplicitParam(name = "transbefore",value = "转换前的pdf地址"),
         @ApiImplicitParam(name = "transafter",value = "转换后的pdf存放的文件夹"),
         @ApiImplicitParam(name = "pdfnum",value = "PDF第几页"),
         @ApiImplicitParam(name = "delnum",value = "第几个图片")
    })
    public void deleteImg(String transbefore,String transafter,int pdfnum,int delnum){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //创建一个PDF实例
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile(transbefore);
        //获取文档的第一页
        PdfPageBase page = doc.getPages().get(pdfnum);
        //删除第一页的第一张图
        page.deleteImage(delnum);
        doc.saveToStream(baos);
        ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        // 删除水印
        handlePdfBook(swapStream,transafter);
        doc.close();
    }

    public static void handlePdfBook(InputStream in,String transafter) {
        try (PDDocument pdfDocument = PDDocument.load(in)) {
            //加载PDF文件
            //处理PDF中的每一页
            for (PDPage page : pdfDocument.getPages()) {
                //解析PDF，找出其中有"xxxx"文字的token也就是COSString元素，找到后把值改掉即可
                PDFStreamParser parser = new PDFStreamParser(page);
                parser.parse();
                List<Object> tokens = parser.getTokens();
                for (Object o : tokens) {
                    if (o instanceof COSString) {
                        COSString cs = (COSString) o;
                        if(cs.toString().contains("Evaluation Warning : The document was created with Spire.PDF for Java.")){
                            cs.setValue(new byte[0]);
                        }
                    }
                }
                //将修改后的token要存进page中去，即修改page中原来的tokens
                PDStream updatedStream = new PDStream(pdfDocument);
                OutputStream out = updatedStream.createOutputStream(COSName.FLATE_DECODE);
                ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
                tokenWriter.writeTokens(tokens);
                out.close();
                page.setContents(updatedStream);
            }
            //将修改后的PDF保存
            pdfDocument.save(transafter+ UUID.randomUUID().toString().replaceAll("-", ""));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void makeQr(OutputStream os,Map<String, Object> qrcodeFields) throws IOException, DocumentException {
        //读取模版
        PdfReader reader = new PdfReader("C:\\Users\\Administrator\\Desktop\\111\\qr.pdf");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper ps = new PdfStamper(reader, bos);
        /*//使用中文字体
        BaseFont bf = BaseFont.createFont(getFontPath("simsun.ttc,1"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
        fontList.add(bf);*/
        AcroFields s = ps.getAcroFields();
        //遍历二维码字段
        for (Map.Entry<String, Object> entry : qrcodeFields.entrySet()) {
            Object value = entry.getValue();
            // 获取属性的类型
            if(value != null){
                //绘制二维码
                float width = 100;
                BarcodeQRCode pdf417 = new BarcodeQRCode(value.toString(), (int)width, (int)width, null);
                //生成二维码图像
                Image image128 = pdf417.getImage();
                //绘制在第一页
                PdfContentByte cb = ps.getOverContent(1);
                //左边距(居中处理)
                float marginLeft = (100 - image128.getWidth()) / 2;
                //条码位置
                image128.setAbsolutePosition(10 + marginLeft, 50);
                //加入条码
                cb.addImage(image128);
            }
        }
        ps.setFormFlattening(true);
        ps.close();

        os.write(bos.toByteArray());
        os.flush();
        os.close();

        bos.close();
        reader.close();
    }

    /**
     * 返回二维码字节数组
     * @param text
     * @param width
     * @param height
     * @return
     * @throws WriterException
     * @throws IOException
     */
    /*public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);//去除多余白边
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height,hints);
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        byte[] pngData = pngOutputStream.toByteArray();
        return pngData;
    }*/

    @GetMapping("/qr")
    public void testqr(String[] args) throws Exception {
        File outputFile = new File("C:\\Users\\Administrator\\Desktop\\111\\test.pdf");

        Map<String, Object> qrcodeFields = new HashMap<String, Object>();
        qrcodeFields.put("qrCode", "http://blog.csdn.net/ruixue0117/article/details/77599808");

        outputFile.createNewFile();
        this.makeQr(new FileOutputStream(outputFile),qrcodeFields);
    }
}
